package com.example.other.chat.worker;

import cn.hutool.json.JSONUtil;
import com.example.authority.common.utils.SpringUtils;
import com.example.authority.domain.User;
import com.example.other.chat.WebSocketServer;
import com.example.other.domain.Chat;
import com.example.other.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;

@Component
@RabbitListener(queuesToDeclare = @Queue(value = "chat_doctor_queue",durable = "false"))
@Slf4j
public class ChatWorker {
    @Autowired
    private ChatService chatService= SpringUtils.getBean(ChatService.class);
    @RabbitHandler
    public void sendMail(Chat chat) throws IOException {
        System.out.println("接收到消息："+chat.getContent());
        //chatService.save(chat);
        Session session = WebSocketServer.sessionPool.get(chat.getDoctorId());
        if(session==null){
            log.info("聊天的用户还未登录，无法发送消息");
        }else {
            if(session.isOpen()){
                session.getBasicRemote().sendText(JSONUtil.toJsonStr(chat));
            }
            else {
                log.info("聊天的用户已经下线，无法发送消息");
            }
        }
    }
}